package com.cerosoft.google.api;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.net.Uri;
import android.util.Log;

public class GoogleAccount {
	private String username = null;
	private String password = null;
	private String auth = null;
	
	public GoogleAccount(String user, String pass) {
		username = user;
		password = pass;
	}
	
	public String getUsername() {
		return username;
	}

	public String getAuth() {
		return auth;
	}

	/**
	 * login to google service, with gmail account and password.
	 * @return The auth string, which have to be used with other API to access the server data. If there is error, the error 
	 *         string will be returned. You have to compare it with error string prefix to determine whether the result is 
	 *         correct or error.
	 * @throws GoogleServiceException 
	 */
	public String loginGoogle() throws GoogleServiceException {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(
				"https://www.google.com/accounts/ClientLogin");
		post.addHeader("Content-Type", "application/x-www-form-urlencoded");
		String postData = String
				.format("accountType=GOOGLE&Email=%s&Passwd=%s&service=cp&source-sm-cp-1.0",
						Uri.encode(username), Uri.encode(password));
		StringEntity se;
		try {
			se = new StringEntity(postData, "UTF-8");
			post.setEntity(se);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		try {
			HttpResponse response = client.execute(post);
			HttpEntity respData = response.getEntity();
			long contentLength = respData.getContentLength();
			InputStream is = respData.getContent();
			Log.i("response", "contentLength = " + contentLength + "(" + is.available() + ")");
			byte[] data = new byte[(int) contentLength];
			is.read(data);
			String respString = new String(data);
			if (response.getStatusLine().getStatusCode() == 200) {
				auth = respString.substring(respString.indexOf("Auth=") + 5);
				Log.i("response", "Auth:" + auth);
			} else {
				String code = String.format("resposne codes = %d", response.getStatusLine().getStatusCode());
				Log.e("response", code);
				throw new GoogleServiceException(code + ":" + respString);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			throw new GoogleServiceException(e.toString());
		} catch (IOException e) {
			e.printStackTrace();
			throw new GoogleServiceException(e.toString());
		}
		return auth;
	}
}
	